package com.lyf.language.learn.atsgg.network;

import org.junit.Test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @AUTHOR LYF
 * @DATE 2022/6/3
 * @VERSION 1.0
 * @DESC
 * 1.socket类似File是一个端点，通过IP+Port定位至进程，开始建立联系，通过IO进行传输
 * ，传输时注意协议规则等问题---计算机网络
 * 2.注意关闭资源（finally），负责浪费资源，产生列如 Connection reset等麻烦
 * 3.serverSocket 绑定主机，Socket()绑定需要通信的目的主机IP--
 * 4.理解TCP/UDP 及 应用场景、原理
 *
 */
public class SocketDemo {
    //------TCP----------
    //失败--reset--，client未关闭资源
    @Test
    public void server(){
        ServerSocket serverSocket = null;
        Socket socket = null;
        InputStream is =null;

        try {
            serverSocket = new ServerSocket(1777);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true){
        try {
            //创建服务端socket，绑定本机IP
            //监听连接
            socket = serverSocket.accept();
            is = socket.getInputStream();

            // 易乱码
//            byte[] bytes = new byte[1024];
//            int len;
//            while((len=is.read(bytes))!=-1){
//
//            }
            byte[] bytes = new byte[1024];
            //ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            int len;
            while((len=is.read(bytes))!=-1){
                byteArrayOutputStream.write(bytes,0,len);
            }
            System.out.println(byteArrayOutputStream.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

            try {
                assert is != null;
                is.close();
                socket.close();
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        }

    }
    @Test
    public void server1() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8899);
        Socket socket = serverSocket.accept();
        InputStream is = socket.getInputStream();

        byte[]bytes = new byte[1024];
        int len;
        while ((len=is.read(bytes))!=-1)
        {
            System.out.println(new String(bytes,0,len));
        }
        System.out.println("来自+"+socket.getInetAddress().getHostName());
        is.close();
        socket.close();
        serverSocket.close();
    }
    @Test
    public void client() throws IOException {
        // 绑定目标的IP
           // 最好用try cath
            Socket socket = new Socket("127.0.0.1",8899);
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("hello".getBytes(StandardCharsets.UTF_8));

            outputStream.close();
            socket.close();

    }

    //------UDP--------






}
